package com.kehutong.payment.admin;

import java.util.List;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;
import com.kehutong.common.util.Token;
import com.kehutong.payment.entity.MerchantSetting;

/**
 * 企业设置
 * @author liuzhen
 */
@MvcAction
@ReqMapping("/admin/setting/merchant")
public class MerchantController {

	@Inject
	private JdbcSession jdbcSession;

	@ReqMapping("/updateMerchantDefault")
	public Object updateMerchantDefault(){
		List<MerchantSetting> list = jdbcSession.findArray(MerchantSetting.class)
												.eq("deleted", false)
												.exe();
		list.forEach(e -> {
			if (e.getId().equals(e.getCompanyNo())) {
				e.setMerchantDefault(true);
			} else {
				e.setMerchantDefault(false);
			}
			jdbcSession.updateById(e);
		});
		return Result.success();
	}

	@ReqMapping("/listByCompanyNo")
	public Object listByCompanyNo(JSONObject jsonObject, Token token) {
		final Page<MerchantSetting> page = jdbcSession.findPage(MerchantSetting.class)
													  .eq(jsonObject, "provider")
													  .eq("companyNo", token.getCompanyNo())
													  .eq("deleted", false)
													  .eq("provider", false)
													  .order("createTime", "desc")
													  .page(jsonObject)
													  .exe();
		
		return Result.success(page);
	}

	@HasPermission("setting:merchant:view")
	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
		final Page<MerchantSetting> page = jdbcSession.findPage(MerchantSetting.class)
													  .eq(jsonObject, "provider")
													  .eq("deleted", false)
													  .order("createTime", "desc")
													  .page(jsonObject)
													  .exe();

		return Result.success(page);
	}

	@HasPermission("setting:merchant:view")
	@ReqMapping("/list/by/company")
	public Object listByCompanyNo(Token token, JSONObject jsonObject) {
		final Page<MerchantSetting> page = jdbcSession.findPage(MerchantSetting.class)
													  .eq(jsonObject, "provider")
													  .eq("companyNo", token.getCompanyNo())
													  .eq("deleted", false)
													  .order("createTime", "desc")
													  .page(jsonObject)
													  .exe();

		return Result.success(page);
	}

	@ReqMapping("/listByProvider")
	public Object listByProvider(JSONObject jsonObject) {
		final Page<MerchantSetting> page = jdbcSession.findPage(MerchantSetting.class)
													  .eq("provider", true)
													  .eq("deleted", false)
													  .order("createTime", "desc")
													  .page(jsonObject)
													  .exe();

		return Result.success(page);
	}

	@HasPermission("setting:merchant:view")
	@ReqMapping("/get")
	public Object get(String id) {
		final MerchantSetting app = Pool.get(MerchantSetting.class, id);
		
		if (Objects.nonEmpty(app.getPid())) {
			final MerchantSetting parent = Pool.get(MerchantSetting.class, app.getPid());
			app.setPname(parent.getMchName());
		}
		
		return Result.success(app);
	}

	@Bean(newInstance=true, copy=true)
	@HasPermission("setting:merchant:edit")
	@ReqMapping("/save")
	public Object save(MerchantSetting app, ValidResult result) {
		if (result.hasError("companyNo", "mchId", "mchName",  "mchSecret", "mchFileId")) {
			return Result.error(0, result.getErrorMessage());
		}

		if (checkUniMerchant(app.getId(), app.getMchId(), app.getAppId(), app.getCompanyNo())) {
			return Result.error(0, "该公司已经存在MA绑定记录");
		}

		MerchantSetting temp = Pool.get(MerchantSetting.class, app.getCompanyNo());
		if (Objects.nonNull(temp) && !temp.isDeleted()){
			jdbcSession.insert(app);
		}else if(Objects.isNull(temp)){
			app.setId(app.getCompanyNo());
			jdbcSession.insert(app);
		}else{
			app.setId(app.getCompanyNo());
			jdbcSession.updateById(app);
		}

		return Result.success();
	}

	@Bean(newInstance=false, copy=true)
	@HasPermission("setting:merchant:edit")
	@ReqMapping("/update")
	public Object update(MerchantSetting app, ValidResult result) {
		if (result.hasError("companyNo", "mchId", "mchName",  "mchSecret", "mchFileId")) {
			return Result.error(0, result.getErrorMessage());
		}

		if (checkUniMerchant(app.getId(), app.getMchId(), app.getAppId(), app.getCompanyNo())) {
			return Result.error(0, "该公司已经存在MA绑定记录");
		}
		
		jdbcSession.updateById(app);
		return Result.success();
	}

	private boolean checkUniMerchant(String id, String mchId, String appId, String companyNo){
		FindOne<MerchantSetting> findOne = jdbcSession.findOne(MerchantSetting.class)
													  .eq("mchId", mchId)
													  .eq("companyNo", companyNo);

		if (Objects.nonEmpty(appId)) {
			findOne.eq("appId", appId);
		} else {
			findOne.markBegin();
			findOne.isEmpty("appId").or();
			findOne.isNull("appId").or();
			findOne.markEnd();
		}

		MerchantSetting merchantSetting = findOne.eq("deleted", false).exe();
		return Objects.nonNull(merchantSetting) && !merchantSetting.getId().equals(id);
	}

	@HasPermission("setting:merchant:edit")
	@ReqMapping("/delete")
	public Object delete(MerchantSetting app) {
		if (Objects.nonNull(app)) {
			if (app.getId().equalsIgnoreCase(app.getCompanyNo())){
				return Result.error(0, "不能删除公司默认商户！");
			}
			app.setDeleted(true);
			jdbcSession.updateById(app);
		}
		
		return Result.success();
	}

}
